package com.example.mobilenet

import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

class FileUtil (private val context: Context ) {

    companion object {
        const val TAG = "FileUtil"
    }

    fun getLocalPathByAssetName(assetFileName: String): String {
        var localFilePath = ""
        val dir = File(context.filesDir.absolutePath + File.separator + "resnet")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        localFilePath = dir.toString() + File.separator + assetFileName
        val file = File(localFilePath)
        if (file.exists()) {
            Log.i(TAG, "getLocalPathByAssetName suc assetFileName: $assetFileName")
            return localFilePath
        }

        copyAssets(assetFileName, localFilePath)
        return localFilePath
    }

    fun copyAssets(pAssetFilePath: String, pDestDirPath: String?) {
        val pContext = context
        val assetManager = pContext.assets
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            inputStream = assetManager.open(pAssetFilePath)
            val outFile = File(pDestDirPath)
            outputStream = FileOutputStream(outFile)
            copyFile(inputStream, outputStream)
            inputStream.close()
            inputStream = null
            outputStream.flush()
            outputStream.close()
            outputStream = null
        } catch (e: IOException) {
            Log.e(TAG, "Failed to copy asset file: $pAssetFilePath", e)
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    Log.w(TAG, e)
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close()
                } catch (e: IOException) {
                    Log.w(TAG, e)
                }
            }
        }
    }

    private fun copyFile(`in`: InputStream, out: OutputStream) {
        val buffer = ByteArray(1024 * 16)
        var read: Int
        while (`in`.read(buffer).also { read = it } != -1) {
            out.write(buffer, 0, read)
        }
    }
}